<template>
  <div>
    <div id="geetest-captcha"></div>
    <p id="wait" class="show">正在加载验证码...</p>
    <button class="error" type="button" @click="error" style="width: 0;padding: 0;border: none"></button>
    <button class="success" type="button" @click="success" style="width: 0;padding: 0;border: none"></button>
  </div>
</template>

<script>
export default {
  name: 'popup，弹出式',
  data () {
    return {
      captchaObj: null,
      API: {
        GET_GEE_TEST: '/geetest'
      }
    }
  },
  props: ['btn_name'],
  created () {
    alphaHub.$on('reset_geetest', status => {
      this.captchaObj.reset() // 调用该接口进行重置
    })

    this.initGeeest()
  },
  methods: {
    error () {
      this.$emit('error')
    },
    success () {
      this.$emit('success')
    },
    initGeeest () {
      let btn_name = this.btn_name
      let geeTestUrl = this.API.GET_GEE_TEST
      let _this = this
      let handlerEmbed = function (captchaObj) {
        _this.captchaObj = captchaObj
        let domBtn = document.getElementsByClassName(btn_name)[0]
        domBtn &&
          (domBtn.onclick = function () {
            let validate = _this.captchaObj.getValidate()
            if (!validate) {
              _this.$emit('error')
              console.log('_this.captchaObj emit error')
            } else {
              _this.$emit('success')
              console.log('_this.captchaObj emit success')
            }
          })
        captchaObj.appendTo('#geetest-captcha')
        _this.captchaObj
          .onReady(function () {
            /**
             * 为避免出现Geetest组件被重复加载到
             * 将holder加入当前引入Geetest的页面dom后，告知父组件 Geetest组件已经加载完毕。
             * 父组件通过该状态（Geetest组件是否加载完毕）在页面组件beforeRouteLeave时决定是否可以立即返回（前往）其他页面。
             */
            _this.$emit('geetestReady')
            document.getElementById('wait').className = 'hide'
          })
          .onSuccess(function () {
            console.log('geetest on success')
          })
          .onError(function () {
            console.log('geetest on error.do reset()')
            _this.captchaObj.reset() // 调用该接口进行重置
          })
      }
      axios.get(geeTestUrl + '?t=' + new Date().getTime()).then(res => {
        let data = res.data
        initGeetest(
          {
            gt: data.gt,
            challenge: data.challenge,
            product: 'popup',
            offline: !data.success,
            lang: 'zh-cn'
          },
          handlerEmbed
        )
      })
    }
  },
  destroyed () {}
}
</script>

<style lang="sass" rel="stylesheet/sass">
    .hide
        display: none
        .geetest_holder.geetest_wind
            left: 100px

</style>
